import { useEffect } from 'react';
import { useIonRouter } from '@ionic/react';
import { App } from '@capacitor/app';

export const useBackButton = () => {
  const router = useIonRouter();

  useEffect(() => {
    App.addListener('backButton', ({ canGoBack }) => {
      if (!canGoBack) {
        App.exitApp();
      } else {
        router.goBack();
      }
    });

    return () => {
      App.removeAllListeners();
    };
  }, [router]);
};